package com.eboss2.sbs.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.weight.DialogUtils;
import com.eboss2.sbs.weight.MyCustomDialog;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.activityManager.MyActivityManager;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.utils.ToastUtils;
import com.tool.utils.utils.UtilPreference;
import com.tool.utils.view.MyCountDownTimer;
import com.tool.utils.view.ShapeView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ActivityRegister extends BaseActivity{

    private final String TAG = "ActivityRegister";
    @BindView(R.id.titleback_btn_back)
    LinearLayout titlebackBtnBack;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.btn_commit)
    ShapeView btnCommit;

    private MyCustomDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        MyActivityManager.getInstance().addActivity(this);
        showView(R.id.titleback_btn_back, true);
        setTvText(R.id.tv_title, "注册");
        showView(R.id.next_sure, false);
    }



    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册 , 防止Activity内存泄漏
        EventBus.getDefault().unregister(this);
    }



    /**
     * 从服务器获取验证码
     */
    private void getValidCode() {
        MyCountDownTimer countDowntimer = new MyCountDownTimer(Config.VOLID_CODE_SECONDS, 1000, tvGetcode,
                getResources().getDrawable(R.drawable.reg_suc_bar1), getResources().getDrawable(R.drawable.reg_suc_bar2));
        countDowntimer.start();

        RequestParams params = new RequestParams();
        params.add("phone", getTvText(R.id.et_phone));
        params.add("type", "2");
        showProgress("正在发送");
        HttpUtil.get(Config.SBS_GET_CODE, params, new HttpUtil.RequestListener() {

            @Override
            public void success(String response) {
                disShowProgress();
                try {
                    JSONObject result = new JSONObject(response);
                    if (result.optInt("code") == -2) {
                        UtilPreference.clearNotKeyValues(mContext);
                        // 退出账号 返回到登录页面
                        MyActivityManager.getInstance().logout(mContext);
                        return;
                    }
                    if (!result.optBoolean("status")) {
                        ToastUtils.CustomShow(mContext, result.optString("message"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }

        });
    }


    /**
     * 提交
     */
    private void doCommit() throws ParseException {

        if (StringUtils.isBlank(etPhone.getText().toString().trim())) {
            ToastUtils.showShort(this, "请输入手机号");
            return;
        }

        if (StringUtils.isBlank(etCode.getText().toString().trim())) {
            ToastUtils.showShort(this, "验证码不能为空");
            return;
        }



        showProgress("加载中...");
        RequestParams params = new RequestParams();
        params.add("phone", getTvText(R.id.et_phone));
        params.add("code", getTvText(R.id.et_code));
        params.add("type", "2");
        HttpUtil.get(Config.SBS_REGISTER, params, requestListener);

    }

    private HttpUtil.RequestListener requestListener = new HttpUtil.RequestListener() {

        @Override
        public void success(String response) {
            disShowProgress();
            try {
                JSONObject result = new JSONObject(response);
                if (result.optInt("code") == -2) {
                    UtilPreference.clearNotKeyValues(mContext);
                    // 退出账号 返回到登录页面
                    MyActivityManager.getInstance().logout(mContext);
                    return;
                }
                if (!result.optBoolean("status")) {
                    ToastUtils.CustomShow(mContext, result.optString("message"));
                } else {
//                    ToastUtils.CustomShow(mContext, result.optString("message"));

                    JSONObject dataStr = result.getJSONObject("data");

                    String description = dataStr.optString("description");
                    String account = dataStr.optString("account");
                    String pwd = dataStr.optString("pwd");

                    description = "请截图保存";

                   dialog = DialogUtils.showDialogSuccess(mContext, "注册成功", description, account, pwd, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            Toast.makeText(mContext, "已复制到粘贴板，可粘贴使用", Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                        }
                    });
                }


            } catch (Exception e) {
                Log.e(TAG, "doCommit() Exception: " + e.getMessage());
            }
        }

        @Override
        public void failed(Throwable error) {
            disShowProgress();
            showE404();
        }
    };


    @OnClick({R.id.titleback_btn_back, R.id.tv_getcode, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleback_btn_back:
                finish();
                break;
            case R.id.btn_commit://提交
                try {
                    doCommit();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.tv_getcode://获取验证码
                if (StringUtils.isBlank(etPhone.getText().toString().trim())) {
                    ToastUtils.showShort(this, "手机号不能为空");
                    return;
                }
                getValidCode();// 从服务器获取验证码
                break;
        }
    }
}
